﻿using ExcelDataReader;
using JYH.Business;
using JYH.Data;
using JYH.Model.API;
using JYH.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Net.Http.Headers;
using System.Web.Hosting;
using OfficeOpenXml;
using System.Web;
using Microsoft.AspNetCore.Cors;
using Newtonsoft.Json;

namespace JYH.Web.MES.Controllers
{
    public class MFGController : ApiController
    {
        private string GetFileName(HttpContentHeaders headers)
        {
            if (headers.ContentDisposition?.FileName != null)
            {
                return headers.ContentDisposition.FileName.Trim('\"');
            }

            // 兼容不同浏览器（如 Chrome 新版本使用 FileNameStar）
            if (headers.ContentDisposition?.FileNameStar != null)
            {
                return headers.ContentDisposition.FileNameStar;
            }

            return "unknown.xls";
        }

        /// <summary>
        /// 备料单导出Excel（基于模板）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage ExportMaterialPreparation(string TradeOrderID)
        {
            try
            {
                Sql sql = new Sql();
                WmsTradeOrderInfoBLL orderInfoBLL = new WmsTradeOrderInfoBLL();
                sql.Append(orderInfoBLL.MPSqlSelect);
                sql.Where($"WmsTradeOrderInfo.TradeType=13");
                sql.Where($"WmsTradeOrderInfo.TradeOrderID='{TradeOrderID}'");
                // 1. 获取主档数据
                var mainData = orderInfoBLL.myDataBase.FirstOrDefault<WmsTradeOrderInfo>(sql);
                sql = new Sql();
                WmsTradeSourceBLL sourceBLL = new WmsTradeSourceBLL();
                sql.Append(sourceBLL.SqlSelect);
                sql.Where($"WmsTradeOrderInfo.TradeType=13");
                sql.Where($"WmsTradeOrderInfo.TradeOrderID='{TradeOrderID}'");
                // 2. 获取明细数据
                var detailList = sourceBLL.myDataBase.Fetch<WmsTradeSource>(sql);

                // 3. 获取模板文件路径（使用HostingEnvironment）
                string templatePath = HostingEnvironment.MapPath("~/UploadFile/Execl/WmsTradeInfo_13.xlsx");

                if (!System.IO.File.Exists(templatePath))
                {
                    return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Excel模板文件不存在");
                }

                // 4. 使用模板创建Excel文件
                FileInfo templateFile = new FileInfo(templatePath);
                using (var package = new ExcelPackage(templateFile))
                {
                    var worksheet = package.Workbook.Worksheets[1];

                    // 5. 填充主档数据到模板指定位置
                    // 假设模板中已有固定的单元格位置
                    worksheet.Cells["B1"].Value = mainData.SourceOrderNO;      // 生产工单
                    worksheet.Cells["B3"].Value = mainData.TradeQty;                 // 备料套数
                    //worksheet.Cells["B2"].Value = mainData.ProductNO;              // 产品料号
                    worksheet.Cells["B2"].Value = mainData.Remark;                    // 备注

                    // 6. 填充明细数据（假设从第8行开始）
                    if (detailList != null && detailList.Count > 0)
                    {
                        int startRow = 5; // 明细数据开始行
                        foreach (var item in detailList)
                        {
                            worksheet.Cells[startRow, 1].Value = item.StationNO;
                            worksheet.Cells[startRow, 2].Value = item.MaterialNO;
                            worksheet.Cells[startRow, 3].Value = item.RequestQty;
                            worksheet.Cells[startRow, 4].Value = item.UnitQty;
                            startRow++;
                        }
                    }

                    // 7. 保存到内存流
                    var stream = new MemoryStream();
                    package.SaveAs(stream);
                    stream.Position = 0;

                    // 8. 返回文件
                    var result = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new ByteArrayContent(stream.ToArray())
                    };
                    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

                    return result;
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }

        /// <summary>
        /// 备料明细导入
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IHttpActionResult> MPImport()
        {
            var message = new ResponseJson<WmsTradeSource>
            {
                Items = new List<WmsTradeSource>(),
                Code = 200,
                Message = "导入成功"
            };

            if (!Request.Content.IsMimeMultipartContent())
            {
                message.Code = 400;
                message.Message = "不支持的媒体类型";
                return BadRequest();
            }

            try
            {
                WmsTradeSourceBLL reciveItemBLL = new WmsTradeSourceBLL();
                // 使用 MultipartMemoryStreamProvider 将文件内容保留在内存中
                var provider = new MultipartMemoryStreamProvider();
                // 异步读取上传内容到内存流
                await Request.Content.ReadAsMultipartAsync(provider);
                // 获取第一个上传的文件流
                if (provider.Contents.Count == 0)
                {
                    message.Code = 500;
                    message.Message = "file is null";
                    return BadRequest();
                }
                string TradeOrderID = string.Empty;
                //获取文件名用于判断扩展名
                string filename = string.Empty;
                // 从内存中读取流
                Stream stream = null;
                foreach (var content in provider.Contents)
                {
                    var headers = content.Headers;
                    var contentDisposition = headers.ContentDisposition;

                    if (contentDisposition == null) continue;

                    // 获取表单字段 TradeOrderID
                    if (contentDisposition.Name?.Trim('\"') == "TradeOrderID")
                    {
                        TradeOrderID = await content.ReadAsStringAsync();
                    }
                    // 获取上传的文件
                    else if (contentDisposition.FileName != null)
                    {
                        filename = GetFileName(headers);
                        stream = await content.ReadAsStreamAsync();
                    }
                }
                //var fileContent = provider.Contents[0];
                //var ReciveOrderID = provider.Contents[1];

                #region 文件上传导入逻辑

                StringBuilder sb = new StringBuilder();
                Sql sql = new Sql();
                string Msg = string.Empty;
                List<WmsTradeSource> Itemlist = new List<WmsTradeSource>();
                // 判断文件类型（xls/xlsx）
                bool isXls = filename.EndsWith(".xls", StringComparison.OrdinalIgnoreCase);
                bool isXlsx = filename.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase);

                if (!isXls && !isXlsx)
                {
                    message.Code = 500;
                    message.Message = "Please upload an Excel file（.xls or .xlsx）";
                    return Content(HttpStatusCode.InternalServerError, message.Message);
                }
                // 使用 ExcelDataReader 读取 Excel 流
                using (var reader = ExcelReaderFactory.CreateReader(stream))
                {
                    var result = reader.AsDataSet(new ExcelDataSetConfiguration()
                    {
                        ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
                        {
                            UseHeaderRow = true // 使用第一行作为列头
                        }
                    });
                    DataTable table = result.Tables.Count > 0 ? result.Tables[0] : null;
                    if (!reciveItemBLL.MPFileDataTable(table, TradeOrderID, ref message))
                    {
                        message.Code = 500;
                        return Content(HttpStatusCode.InternalServerError, message.Message);
                    }
                    else
                    {
                        message.Message = $"Successfully imported {message.TotalCount} records";
                    }
                }

                #endregion 文件上传导入逻辑
            }
            catch (Exception ex)
            {
                message.Code = 500;
                message.Message = "Error：" + ex.Message;
                return Content(HttpStatusCode.InternalServerError, message.Message);
            }
            return Ok(message);
        }

        /// <summary>
        ///   备料单备料库存明细计算
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult MPItemList([FromBody] LigthList<WmsTradeSource> Info)
        {
            ResponseJson<WmsTradeSource> json = new ResponseJson<WmsTradeSource>();
            json.Items = new List<WmsTradeSource>();
            string Msg = string.Empty;
            try
            {
                List<WmsTradeSource> lists = new List<WmsTradeSource>();
                WmsTradeSourceBLL barcodeInfoBLL = new WmsTradeSourceBLL();
                bool res = barcodeInfoBLL.PrepareMaterialForOrder(Info, ref json);
                if (!res)
                {
                    return Content(HttpStatusCode.InternalServerError, json.Message);
                }
                json.Items = new List<WmsTradeSource>();
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, json.Message);
            }
        }
    }
}